import Vue from 'vue'
import Vuex from 'vuex'
import { getCartList, changeCount, delGoods } from '@/api/cart'
Vue.use(Vuex)

export default ({
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  getters: {
    cartTotal (state) {
      return state.cartList.reduce((sum, item, index) => sum + item.goods_num, 0)
    },
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => sum + item.goods_num, 0)
    },
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => {
        return sum + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },
    // 是否选中 （小选框控制全选框）
    isChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  },
  mutations: {
    // 修改cartList
    setCartList (state, newList) {
      state.cartList = newList
    },
    // 基本选中
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    // 全选
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    // 修改商品数量
    changeCount (state, { goodsId, goodsNum }) {
      // 本地修改
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: {
    async getCartAction (content) {
      // 获取商品列表
      const { data } = await getCartList()
      // console.log(res)
      // 得到的数据不包含商品的选中状态， 手动添加这个属性t
      data.list.forEach(element => {
        element.isChecked = true
      })
      // 提交mutation 修改数据
      content.commit('setCartList', data.list)
    },

    // 更新商品数量
    async changeCountAction (content, { goodsId, goodsNum, goodsSkuId }) {
      await changeCount(goodsId, goodsNum, goodsSkuId)
      // console.log(res)
      // 提交mutation 修改数据
      // 本地修改，
      content.commit('changeCount', { goodsId, goodsNum })
    },

    // 删除商品
    async delSelectAction (content) {
      // 找到选中的商品
      const selCartList = content.getters.selCartList
      const cartIds = selCartList.map(item => item.id)
      await delGoods(cartIds)
      // console.log(res)
      // 重新渲染 获取商品列表
      content.dispatch('getCartAction')
    }
  },
  modules: {
  }
})
